package com.yc.pos;

import android.util.Log;

import com.attendance.sz.utils.SwipeAction;
import com.attendance.sz.utils.Version;
import com.hwangjr.rxbus.RxBus;

/**
 * Created by Administrator on 2015-11-20.
 */
public class Packet {
    public static final String HST_FLAG = "HST";
    public static final String SLV_FLAG = "SLV";
    public String flag;
    public int cmd;
    public int length;
    public int state;
    public byte[] data;

    public Packet(int cmdCode ,byte[] dataBody){
        flag = HST_FLAG;
        length = dataBody.length;
        cmd = cmdCode;
        data = dataBody;
    }

    public Packet(String hexPacket){
        flag = SLV_FLAG;
        //TODO----
//        RxBus.get().post(SwipeAction.UP,hexPacket );
//        Log.d("TODO",hexPacket);
        String hexCmd = hexPacket.substring(6, 8);
        cmd = DigitalUtil.hexString2DecInt(hexCmd);

        String hexLength = hexPacket.substring(8,12);
        length = DigitalUtil.hexString2DecInt(hexLength);

        String hexState = hexPacket.substring(16,18);
        state = DigitalUtil.hexString2DecInt(hexState);

        int c = hexPacket.length()-2;
        String hexData = hexPacket.substring(18,c);
        data = DigitalUtil.HexString2Bytes(hexData);
    }



    public byte[] encode(){
        String machineId = Version.GetMachineNo();
        int iMachineNo = Integer.valueOf(machineId);//转成十进制的数字12
        String strGet16Len = DigitalUtil.Get16Len(iMachineNo);//转数字转16进制字串同时变小写,如12-->c
        String hexMachineId = GetTempValue(strGet16Len, 4);//转成四位的字符串,不够前面补0

        String str16Length = DigitalUtil.Get16Len(length);//转数字转16进制字串同时变小写,如12-->c
        String hexLength = GetTempValue(str16Length, 4);//转成四位的字符串,不够前面补0

        String str16Cmd = DigitalUtil.Get16Len(cmd);//转数字转16进制字串同时变小写,如12-->c
        //String hexCmd = GetTempValue(str16Cmd, 4);//转成四位的字符串,不够前面补0
        String hexCmd = str16Cmd;

        String hexHead = DigitalUtil.Bytes2HexString(flag.getBytes());
        String hexData = DigitalUtil.Bytes2HexString(data);
        StringBuilder sb = new StringBuilder();
        sb.append(hexHead);
        sb.append(hexCmd);
        sb.append(hexLength);
        sb.append(hexMachineId);
        sb.append(hexData);
        String hexCrc = getCheckNo(sb.toString());
        sb.append(hexCrc);

        return DigitalUtil.HexString2Bytes(sb.toString());
    }

    public static String getCheckNo(String value16)
    {
        byte[] byteArray= DigitalUtil.HexString2Bytes(value16);
        value16= DigitalUtil.Get16Len(DigitalUtil.GetSocketCrc(byteArray, byteArray.length));
        value16=GetTempValue(value16,2);
        return value16;
    }

    public static String GetTempValue(String value,int length)
    {
        int len=value.length();
        String strFlag="";
        if(len<length)
        {
            for(int i=0;i<length-len;i++)
            {
                strFlag=strFlag+"0";
            }
        }

        return strFlag+value;
    }
}
